﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Collections;
using Department.App_Code;

namespace Department
{
    public partial class Default : System.Web.UI.Page
    {
        private string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
        private int depID;
        protected void Page_Load(object sender, EventArgs e)
        {
            string pageName = string.Empty;
            string id = Request.Params["ID"];
            string pageText = string.Empty;
            int type;
            bool result;
            string userID;
            int pageID;
            depID = DepartmentProperties.GetDepartmentID(Request["dept"]);

            if (!Page.IsPostBack)
            {
                if (id == null)
                {
                    id = PageProperties.GetMainPageID().ToString();
                }

                if (!(id == null))
                {
                    using (SqlConnection conn = new SqlConnection(strConnString))
                    {
                        System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
                        try
                        {
                            userID = mu.ProviderUserKey.ToString();
                        }
                        catch (NullReferenceException)
                        {
                            userID = "guest";
                        }
                        try
                        {
                            conn.Open();

                            pageID = PageProperties.GetPageID(id);
                            if (pageID == 0)
                                Response.Redirect("/Default.aspx?id=" + PageProperties.GetMainPageID());

                            result = PageProperties.CallFunction(pageID, userID);

                            if (!result)
                                MustLoginLabel.Visible = true;
                            else
                            {
                                //Get Page Name
                                pageName = PageProperties.GetPageName(id);
                                Master.FindControl("PageNameLabel").Controls.Add(new LiteralControl(pageName));

                                //Get Site content
                                pageText = PageProperties.GetCnt(id);
                                Master.FindControl("mainContentHolder").Controls.Add(new LiteralControl(pageText));

                                //Get Dynamic contents s type
                                type = PageProperties.GetDynCntType(id);

                                this.Title = pageName + " | Информационни технологии и комуникации"; // The Title of every Page is formed by the name of the department plus the page name

                                switch (type)
                                {
                                    case 0: //No dynamic content
                                        {
                                            //Show nothing
                                        } break;
                                    case 1: //Lecturers
                                        {
                                            string sql = "SELECT LecturersFromDB.DegreeName, LecturersFromDB.RankName, LecturersFromDB.LecturerFullNameBG AS Name, LecturersFromDB.LecturerID as ID, Lecturers.PictureLink, isnull(Lecturers.TypeID, @Type) as TypeID " +
                                                "FROM Lecturers RIGHT OUTER JOIN LecturersFromDB ON Lecturers.LecturerDbID = LecturersFromDB.LecturerID WHERE (LecturersFromDB.DepartmentID = @DepID) AND isnull(Lecturers.IsHidden,0) = 0 ORDER BY Name";
                                            SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                            ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                            ada.SelectCommand.Parameters.AddWithValue("@Type", type);
                                            DataTable dt = new DataTable();
                                            ada.Fill(dt);
                                            ListLecturers.DataSource = dt;
                                            ListLecturers.DataBind();
                                            ListLecturers.Visible = true;

                                        } break;

                                    case 2: //News 
                                        {
                                            FilterHeader.Visible = true;
                                            FilterLnkBtn.Text = "Търсене в Новини";

                                            string sql = @"SELECT ID, Heading, Date, SUBSTRING(Text, 1, 100) AS Text, TypeID FROM News WHERE (IsHidden = 0) AND (FacDeptID=@DepID) ORDER BY Date DESC";
                                            SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                            ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                            DataTable dt = new DataTable();
                                            ada.Fill(dt);
                                            ListNews.DataSource = dt;
                                            ListNews.DataBind();
                                            ListNews.Visible = true;

                                        } break;

                                    case 3: //Disciplines 
                                        {
                                            string sql = "SELECT DisciplineFromDB.DisciplineName AS Name, ISNULL( Disciplines.TypeID, @Type) AS TypeID, SpecialtiesFromDB.DepartmentID,  DisciplineFromDB.DisciplineID AS ID " +
                                                "FROM SpecialtiesFromDB INNER JOIN DisciplineFromDB ON  SpecialtiesFromDB.SpecID =  DisciplineFromDB.SpecID LEFT OUTER JOIN Disciplines ON  DisciplineFromDB.DisciplineID =  Disciplines.DisciplineDbID " +
                                                "WHERE (SpecialtiesFromDB.DepartmentID = @DepID) AND (ISNULL(Disciplines.IsHidden, 0) = 0) ORDER BY Name";
                                            SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                            ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                            ada.SelectCommand.Parameters.AddWithValue("@Type", type);
                                            DataTable dt = new DataTable();
                                            ada.Fill(dt);
                                            ListDisc.DataSource = dt;
                                            ListDisc.DataBind();
                                            ListDisc.Visible = true;
                                        }
                                        break;
                                    case 4: //Events
                                        {
                                            FilterHeader.Visible = true;
                                            FilterLnkBtn.Text = "Търсене в Събития";

                                            string sql = "SELECT ID, Name, EventDate, SUBSTRING(Description, 1, 100) AS Description, TypeID FROM Events WHERE (IsHidden = 0) AND (FacDeptID=@DepID) ORDER BY PublishDate";
                                            SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                            ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                            DataTable dt = new DataTable();
                                            ada.Fill(dt);
                                            ListEvents.DataSource = dt;
                                            ListEvents.DataBind();
                                            ListEvents.Visible = true;
                                        }
                                        break;
                                    case 6: //Documents
                                        {
                                            if (!Request.IsAuthenticated)
                                            {
                                                MustLoginLabel.Visible = true;
                                                LoginLink.Visible = true;
                                            }
                                            else
                                            {
                                                //FilterHeader.Visible = true;
                                                //FilterLnkBtn.Text = "Търсене в Документи";
                                                string sql = "SELECT ID, Name, SUBSTRING(Description, 1, 100) AS Description, Link FROM Documents WHERE (IsHidden = 0) AND (FacDeptID=@DepID) ORDER BY Date";
                                                SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                                ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                                DataTable dt = new DataTable();
                                                ada.Fill(dt);
                                                ListDocs.DataSource = dt;
                                                ListDocs.DataBind();
                                                LabelDocsDropDown.Visible = true;
                                                DocTypeDropDown.Visible = true;
                                                ListDocs.Visible = true;
                                            }
                                        }
                                        break;
                                    case 5: //Education Materials
                                        {
                                            if (!Request.IsAuthenticated)
                                            {
                                                MustLoginLabel.Visible = true;
                                            }
                                            else
                                            {
                                                string sql = "SELECT DISTINCT D.DisciplineName AS Name, D.DisciplineID AS ID, EM.TypeID FROM SpecialtiesFromDB AS s INNER JOIN DisciplineFromDB AS D ON s.SpecID = D.SpecID " +
                                                    "INNER JOIN EducationMaterial AS EM ON D.DisciplineID = EM.DiscID WHERE (s.DepartmentID = @DepID) AND (ISNULL(EM.IsHidden, 0) = 0) ORDER BY Name";
                                                SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                                ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                                DataTable dt = new DataTable();
                                                ada.Fill(dt);
                                                ListDicsEduMaterials.DataSource = dt;
                                                ListDicsEduMaterials.DataBind();
                                                ListDicsEduMaterials.Visible = true;
                                            }
                                        }
                                        break;
                                    default: // Dynamic Content
                                        {
                                            string sql = "SELECT ID, Name, TypeID FROM DynamicContent WHERE (IsHidden = 0) AND (FacDeptID=@DepID) AND TypeID=@type ORDER BY Name";
                                            SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                            ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                            ada.SelectCommand.Parameters.AddWithValue("@Type", type);
                                            DataTable dt = new DataTable();
                                            ada.Fill(dt);
                                            ListDynCnt.DataSource = dt;
                                            ListDynCnt.DataBind();
                                            ListDynCnt.Visible = true;
                                        }
                                        break;
                                }
                            }
                        }

                        catch (SqlException)
                        {}
                        finally
                        {
                            conn.Close();
                        }
                    }
                }
            }
        }

        protected void DocTypeDropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(strConnString))
            {
                try
                {
                    conn.Open();
                    string selectedValue = DocTypeDropDown.SelectedValue.ToString();

                    switch (selectedValue)
                    {
                        case "0": // All
                            {
                                string sql = "SELECT ID, Name, Description, Link FROM Documents WHERE (IsHidden = 0) AND (FacDeptID=@DepID) ORDER BY Date";
                                SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                DataTable dt = new DataTable();
                                ada.Fill(dt);
                                ListDocs.DataSource = dt;
                                ListDocs.DataBind();
                            } break;
                        case "1": // Events
                            {
                                string sql = "SELECT D.Name, D.Description, D.Link FROM Documents AS D INNER JOIN DocumentsForEvents ON D.ID = DocumentsForEvents.DocID WHERE (D.IsHidden = 0) AND (D.FacDeptID=@DepID) ORDER BY D.Date";
                                SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                DataTable dt = new DataTable();
                                ada.Fill(dt);
                                ListDocs.DataSource = dt;
                                ListDocs.DataBind();
                            } break;
                        case "2": // News
                            {
                                string sql = "SELECT D.Name, D.Description, D.Link FROM Documents AS D INNER JOIN DocumentsForNews ON D.ID = dbo.DocumentsForNews.DocID WHERE (D.IsHidden = 0) AND (D.FacDeptID=@DepID) ORDER BY D.Date";
                                SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                DataTable dt = new DataTable();
                                ada.Fill(dt);
                                ListDocs.DataSource = dt;
                                ListDocs.DataBind();
                            } break;
                        case "3": // Other
                            {
                                string sql = "SELECT Documents.ID, Documents.Name, Documents.Description, Documents.Link FROM Documents LEFT OUTER JOIN DocumentsForContent " +
                                    "ON Documents.ID = DocumentsForContent.DocID LEFT OUTER JOIN DocumentsForEvents ON Documents.ID = DocumentsForEvents.DocID LEFT OUTER JOIN " +
                                    "DocumentsForNews ON Documents.ID = DocumentsForNews.DocID LEFT OUTER JOIN DocumentsToEduMaterials ON Documents.ID = DocumentsToEduMaterials.DocID " +
                                    "WHERE (Documents.IsHidden = 0) AND (DocumentsForEvents.DocID IS NULL) AND (DocumentsForNews.DocID IS NULL) AND (DocumentsToEduMaterials.DocID IS NULL) AND (Documents.FacDeptID=@DepID) ORDER BY Documents.Date";
                                SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
                                ada.SelectCommand.Parameters.AddWithValue("@DepID", depID);
                                DataTable dt = new DataTable();
                                ada.Fill(dt);
                                ListDocs.DataSource = dt;
                                ListDocs.DataBind();
                            } break;
                    }
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        protected void FilterButton_Click(object sender, EventArgs e)
        {
            bool flag = false;
            string date;
            string text;
            string name;
            int type;

            if (FilterTitleTextBox.Text.Equals("") && FilterDateTextBox.Text.Equals("") && FilterDescTextBox.Text.Equals(""))
            {
                FilterLabel.Text = "Моля, изберете поле за филтриране!";
                FilterLabel.Visible = true;
            }
            else
            {
                date = FilterDateTextBox.Text.ToString().Trim();
                text = FilterDescTextBox.Text.ToString().Trim();
                name = FilterTitleTextBox.Text.ToString().Trim();

                type = PageProperties.GetDynCntType(Request.Params["ID"]);
                DataTable dt = new DataTable();
                switch (type)
                {
                    case 2:
                        {
                            dt = CallStoredProcedure.FilterNews(name, date, text, depID);
                            ListNews.DataSource = dt;
                            if (!(dt.Rows.Count == 0))
                            {
                                ListNews.DataBind();
                                NewsUpdatePanel.Update();
                                flag = true;
                            }
                        } break;
                    case 4:
                        {
                            dt = CallStoredProcedure.FilterEvents(name, date, text, depID);
                            ListEvents.DataSource = dt;
                            if (!(dt.Rows.Count == 0))
                            {
                                ListEvents.DataBind();
                                EventsUpdatePanel.Update();
                                flag = true;
                            }

                        } break;
                }

                if (!flag) // No items found
                {
                    FilterLabel.Visible = true;
                    FilterLabel.Text = "Няма намерени резултати.";
                }
            }

        }
    }
}

